package com.huichenghe.xinlvsh01.expand_activity;

import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.huichenghe.xinlvsh01.Adapter.MyViewPagerAdapter;
import com.huichenghe.xinlvsh01.DbEntities.MyDBHelperForDayData;
import com.huichenghe.xinlvsh01.R;
import com.huichenghe.xinlvsh01.Utils.LocalDataSaveTool;
import com.huichenghe.xinlvsh01.Utils.MyConfingInfo;
import com.huichenghe.xinlvsh01.fragment.MovementFragment;
import com.huichenghe.xinlvsh01.fragment.SleepingFragment;
import com.huichenghe.xinlvsh01.slide.DeviceAmdActivity;

import java.util.ArrayList;

public class Detail_activity extends AppCompatActivity
        implements MovementFragment.OnFragmentInteractionListener,
                   SleepingFragment.OnFragmentInteractionListener
{
    private ViewPager mViewPager;
    private MovementFragment mMovementFragment;
    private SleepingFragment mSleepingFragment;
    private ArrayList<Fragment> fArrayList;
    private ArrayList<String> listString;
    private TextView mTitle;
    private TextView mDataSelect;
    private PopupWindow timeWindow;
    private MyRecycleView myRecycleView;


    boolean isShownPagerOne = true;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_detail_ctivity);
//        settingTheStatebarAndNavigationbar();
        init();





    }


    /**
     * 获取状态栏高度
     */
    private int getStateBarHight()
    {
        int stateBarHight = 0;

        int resId = getResources().getIdentifier("status_bar_hight", "dimen", "android"); // 获取stateBar的Id
        if(resId > 0)
        {
            stateBarHight = getResources().getDimensionPixelSize(resId);                  // 通过Id，获取像素值
        }
        return stateBarHight;
    }


    /**
     * 初始化基本配置
     */
    private void init()
    {


        myRecycleView = new MyRecycleView();
        listString = new ArrayList<String>();


        // 时间选择
        mDataSelect = (TextView)findViewById(R.id.day_select);
        mDataSelect.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {

                listString.clear();
                View view = getTheHistroyDataViewLayout();
                timeWindow = new PopupWindow(view,
                        LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
                timeWindow.setFocusable(true);
                timeWindow.setBackgroundDrawable(new BitmapDrawable());
                timeWindow.setAnimationStyle(R.style.mypopupwindow_anim_style);
                timeWindow.showAtLocation(view, Gravity.BOTTOM, 0, getWindowManager().getDefaultDisplay().getHeight());
                timeWindow.setOnDismissListener(new PopupWindow.OnDismissListener()
                {
                    @Override
                    public void onDismiss()
                    {
                        timeWindow = null;
                    }
                });

            }
        });





//        int stateBarHeight = getStateBarHight();
//        mTitle.setPadding(0, stateBarHeight, 0, 0);
        // 导航条
        Toolbar toolbar = (Toolbar)findViewById(R.id.detail_toolbar);
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        toolbar.setNavigationIcon(R.drawable.back);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Detail_activity.this.onBackPressed();
            }
        });
        toolbar.setOnMenuItemClickListener(myMenuListener);

        // fragment对象
        mMovementFragment = MovementFragment.newInstance("1234", "5678");
        mSleepingFragment = SleepingFragment.newInstance("0987", "5432");
        // fragment集合
        fArrayList = new ArrayList<>();
        fArrayList.add(mMovementFragment);
        fArrayList.add(mSleepingFragment);
        // viewpager
        mViewPager = (ViewPager)findViewById(R.id.detail_viewpager);
        MyViewPagerAdapter fAdapter = new MyViewPagerAdapter(getSupportFragmentManager(), fArrayList);
        // 为Viewpager设置Adapter
        mViewPager.setAdapter(fAdapter);
        mViewPager.setCurrentItem(0);   // 设置当前页面
        // 设置页面切换监听
        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            // pager滑动监听
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
            {

            }
            // paget切换监听
            @Override
            public void onPageSelected(int position)
            {
                if(position == 0)
                {
//                    sleepDetail_button.setImageResource(R.drawable.sleeping);
                }
                else if(position == 1)
                {
//                    sleepDetail_button.setImageResource(R.drawable.movement);
                }
            }

            // pager滑动状态监听，即，是正在滑动还是已滑动停止
            @Override
            public void onPageScrollStateChanged(int state)
            {

            }
        });
    }


    @Override
    protected void onResume()
    {
        super.onResume();




    }

    /**
     * 设置沉浸式状态栏和底部虚拟键全屏
     */
    private void settingTheStatebarAndNavigationbar() {
//        // 透明状态栏
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //底部虚拟键透明
//        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
    }



//    View.OnClickListener clickListener = new View.OnClickListener()
//    {
//        @Override
//        public void onClick(View v)
//        {
//           switch (v.getId())
//           {    // 点击pager切换按钮， 如果是第一张，则显示第二张，相反亦然
//               case R.id.sleeping_viewpager_button:
//                   if(isShownPagerOne)
//                   {
//                       mViewPager.setCurrentItem(1);
//                       isShownPagerOne = false;
//                       sleepDetail_button.setImageResource(R.drawable.movement);
//                   }
//                   else if(!isShownPagerOne)
//                   {
//                       mViewPager.setCurrentItem(0);
//                       isShownPagerOne = true;
//                       sleepDetail_button.setImageResource(R.drawable.sleeping);
//                   }
//                   break;
//           }
//        }
//    };


    //toolbar的menu监听器
    Toolbar.OnMenuItemClickListener myMenuListener = new Toolbar.OnMenuItemClickListener()
    {
        @Override
        public boolean onMenuItemClick(MenuItem item)
        {
            switch (item.getItemId())
            {
                case R.id.share_main:
                    startActivity(ShareActivity.class);
                    break;
                case R.id.trend_main:
                    startActivity(TrendActivity.class);
                    break;
            }


            return true;
        }
    };

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main,menu);
        return true;
    }

    private void startActivity(Class<?> cla)
    {
        Intent intent = new Intent();
        intent.setClass(Detail_activity.this, cla);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    @Override
    public void onFragmentInteraction(Uri uri)
    {
    }


    /**
     * 解析xml并呈现数据都在此方法上进行
     * @return
     */
    private View getTheHistroyDataViewLayout()
    {
        // 查询有数据的日期
        String userAccount = LocalDataSaveTool.getInstance(Detail_activity.this).readSp(MyConfingInfo.USER_ACCOUNT);
        Cursor mCursor = MyDBHelperForDayData.getInstance(Detail_activity.this)
                .selectTheDay(Detail_activity.this, userAccount);
        parserTheDayCursor(mCursor);


        View view = LayoutInflater.from(Detail_activity.this).inflate(R.layout.show_histroy_data_layout, null);
        RecyclerView recyclerView = (RecyclerView)view.findViewById(R.id.show_the_data_in_popwindow);
        recyclerView.setLayoutManager(new LinearLayoutManager(Detail_activity.this));
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(myRecycleView);

        return view;
    }

    private void parserTheDayCursor(Cursor mCursor)
    {
        if(mCursor.getCount() != 0)
        {
            if(mCursor.moveToFirst())
            {
                do
                {
                    String day = mCursor.getString(mCursor.getColumnIndex("day"));
                    listString.add(day);
                }while (mCursor.moveToNext());
            }
        }

        myRecycleView.notifyDataSetChanged();
    }


    /**
     * 更新所有需要显示的数据
     * @param day
     */
    private void updateAllDataAtThatDay(String day)
    {
        mMovementFragment.updateDayData(day);
        mSleepingFragment.updateSleepData(day);



    }


    class MyRecycleView extends RecyclerView.Adapter<MyRecycleView.MyViewHolder>
    {


        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
        {
            View viewRoot = LayoutInflater.from(Detail_activity.this).inflate(R.layout.item_for_histroy_data, parent, false);
            return new MyViewHolder(viewRoot);
        }

        @Override
        public void onBindViewHolder(MyViewHolder holder, final int position)
        {
            holder.mTime.setText(listString.get(position));
            // 设置点击监听
            holder.mTime.setOnClickListener(new View.OnClickListener()
            {
                @Override
                public void onClick(View v)
                {
                   String day = listString.get(position);
                    // 更新所有显示
                    updateAllDataAtThatDay(day);



                }
            });
        }



        @Override
        public int getItemCount()
        {
            return listString.size();
        }

        class MyViewHolder extends  RecyclerView.ViewHolder
        {
            TextView mTime;
            public MyViewHolder(View itemView)
            {
                super(itemView);
                mTime = (TextView)itemView.findViewById(R.id.show_data_item);

            }
        }


    }






}
